<template>
	<!-- <view class="containerbox bgc-white" style="background: linear-gradient(180deg,#c4f2e7,#f5f8e5,#f1f1f1);" :style="'--font_title: '+font_title+'rpx;--font_cons:'+font_cons+'rpx'"> -->
	<view class="containerbox bgc-white" :style="'--font_title: '+font_title+'rpx;--font_cons:'+font_cons+'rpx'">
		<uv-navbar :leftText="'文章阅读'" auto-back placeholder bg-color="transparent">
			<template v-slot:right>
				<view class="flex items-center pr-10" :style="{ marginRight: navRight }">
					<view class="flex flex-column justify-center items-center mr-10" style="font-size: 18rpx" v-if="!loading && !isselect">
						<image :src="`https://assets-1315727392.cos.ap-chongqing.myqcloud.com/yingyu/png/pic14.png`" style="width: 44rpx;height: 20rpx" />
						{{ formattedReadTime }}
					</view>
					
					<view class="px-10 -mr-10" @tap="fontStatus = !fontStatus">
						<image :src="`https://assets-1315727392.cos.ap-chongqing.myqcloud.com/questbank/png/pic16.png`" class="w-45 h-45" />
					</view>
				</view>
			</template>
		</uv-navbar>
		
		<scroll-view scroll-y class="containerbox relative px-20">
			<view style="height: 2rpx" />
			<view
				:key="item.id" 
				v-for="item, index in courseArticleParagraphlist" 
				style="border: 1rpx dashed transparent;border-radius: 12rpx;margin-top: -2rpx"
				@tap="courseArticleParagraphIndex = courseArticleParagraphIndex === index ? -1 : index"
				:style="{ borderColor: courseArticleParagraphIndex === index ? '#1abc9c !important' : 'transparent' }"
			>
				<view style="width: 100%;transition: height .3s" :style="{ height: `${isTranslation ? 40 : 20}rpx` }" />
				<view style="padding: 0 25rpx">
					<c_reac_text :text="item.english" :articleId="props.articleId" ref="reactextRef" @callback="setNewWord" />
				</view>
				<view 
					class="translation-view" 
					style="overflow: hidden;transition: height .3s, opacity .3s" 
					:style="{ height: isTranslation ? `${item.rect?.height}px` : 0, opacity: Number(isTranslation) }"
				>
					<view class="translation-view-text">
						<view style="line-height: 40rpx;font-size: calc(var(--font_cons, 32) - 10rpx);color: #909399;padding: 0 25rpx">{{ item.chinese }}</view>
						<view 
							:style="`border-top: 1rpx dashed #eeeeee;margin-top: 50rpx`" 
							v-if="index !== courseArticleParagraphlist.length - 1 && courseArticleParagraphIndex - 1 !== index && courseArticleParagraphIndex !== index" 
						/>
					</view>
				</view>
				<view 
					style="width: 100%;transition: height .3s"
					:style="{ height: `${index === courseArticleParagraphlist.length - 1 && isTranslation ? 40 : isTranslation ? 0 : 20}rpx` }"
				/>
			</view>
		</scroll-view>
		
		<view class="flex items-center justify-between bottombox">
			<view class="flex-1 flex items-center pr-30" style="gap: 30rpx">
				<view
					@click="playEvent"
					style="transition: all .3s"
					hover-class="botton-active"
					:class="isplayStatus ? 'bgc-primary2' : 'bgc-white'"
					class="w-90 h-90 bgc-white round-30 flex items-center relative justify-center text-30 border-primary2 text-primary2" 
				>
					<view class="absolute" style="left: 12rpx; top: 17rpx" v-if="topicData?.voiceFile?.url">
						<c_trumpet :play="isplayStatus" :selected="isplayStatus" />
					</view>
					
					<template v-else>
						<image :src="`${imgPath}loading.gif`" class="w-40 h-40" />
						<view class="bgc-primary2 absolute text-24 text-white round-10" style="white-space: nowrap;transform: translateY(-160%);left: 0;top: 0;letter-spacing: 2rpx;padding: 8rpx 12rpx">
							合成中
							<text class="absolute" style="border: 15rpx solid transparent;transform: translate(-50%, 100%);bottom: 1rpx;left: 45rpx;border-bottom: none;border-top-color: #1abc9c" />
						</view>
					</template>
				</view>
				
				<view 
					@click="switchStatus"
					style="transition: all .3s"
					:class="reactextStatus ? 'bgc-primary2' : 'bgc-white'"
					class="w-90 h-90 round-30 flex items-center justify-center bgc-white border-primary2" 
				>
					<uni-icons type="flag" size="40rpx" v-if="!reactextStatus" color="#00c386" />
					<uni-icons type="flag-filled" size="40rpx" v-else color="white" />
				</view>
				
				<view
					class="w-90 h-90 spell spell-danciguanli bgc-white round-30 flex items-center relative justify-center text-34 border-primary2" 
					style="color: #00c386;"
					hover-class="botton-active"
					@click="goWord">
				</view>
				
				<view
					hover-class="botton-active"
					style="transition: all .3s"
					@click="isTranslation = !isTranslation"
					:class="isTranslation ? 'bgc-primary2 text-white' : 'bgc-white text-primary2'"
					class="w-90 h-90 round-30 flex items-center relative justify-center text-34 border-primary2" 
				>
					译
				</view>
			</view>
			<view class="btn bgc-primary2" @click="handleStart">
				<uv-transition :show="!!exerInfo.status">
					<template v-if="topicData.questions?.length">
						{{ isselect ? '查看解析' : '做题' }}
					</template>
					
					<view v-else class="flex items-center text-30">
						题目
						<image :src="`${imgPath}loading.gif`" class="w-25 h-25 ml-8" />
					</view>
				</uv-transition>
			</view>
		</view>
		
		<audio />
	</view>
	
	<uv-popup ref="popupRef" mode="bottom" @change="popupStatusEvent" round="32rpx" backgroundColor="#fff">
		<view class="bgc-white">
			<view class="text-32 text-center py-20">关卡列表</view>
			<scroll-view scroll-y style="max-height: 800rpx;">
				<c_ranklist v-if="isListShow" :examId="submitData.exerciseId" isGop @handle="handleRank" :courseId="detail.course?.id" />
			</scroll-view>
		</view>
	</uv-popup>
	
	<uv-popup ref="ExamPopupRef" mode="bottom" round="32rpx" backgroundColor="#fff" @change="handleExamPopup">
		<view class="bgc-white">
			<view class="relative flex items-center justify-between pt-40 pb-60">
				<view class="text-36 pl-40  font-weight-700">答题</view>
				<view class="flex items-center mr-40">
					<image :src="`https://assets-1315727392.cos.ap-chongqing.myqcloud.com/yingyu/png/pic15.png`" class="w-50 h-50 mr-20" @tap="cardEvent" />
					<view class="flex flex-column justify-center items-center mr-20" style="font-size: 18rpx;">
						<image :src="`https://assets-1315727392.cos.ap-chongqing.myqcloud.com/yingyu/png/pic14.png`" mode="heightFix" style="height: 20rpx;" />
						{{ formattedTime }}
					</view>
					
					<uv-icon name="close" size="32rpx" @tap="ExamPopupRef?.close()" />
				</view>
			</view>
			<!-- <c_exam ref="examRef" :list="topicData?.article?.questions" @takeFun="takeFun" @submit="handleSubmit" :read="isselect" :useranswerlist="useranswerlist" /> -->
		</view>
	</uv-popup>
	
	<dialog_font v-model="fontStatus" @callback="setupFontFun" />
</template>

<script setup>

	import { imgPath } from '@/common/config'
	import readApi from '@/common/apis/read';
	import c_exam from './components/exam.vue';
	import useFont from './components/useFont';
	import c_trumpet from './components/trumpet.vue';
	import c_ranklist from './components/ranklist.vue';
	import c_reac_text from './components/reac_text.vue';
	import dialog_font from './components/dialog_font.vue';
	import { onLoad, onHide, onShow } from "@dcloudio/uni-app";
	import { computed, onMounted, reactive, ref, onBeforeUnmount, nextTick, getCurrentInstance } from 'vue';
	import { getArticleDetail_api, getExerDetail_api, postStartExer_api, postSaveAnswer_api, postSubmitExer_api, getArticleWordsList_api } from '@/common/apis/course';
	
	
	/** pad */
	const pad = uni.getSystemInfoSync().deviceType == 'pad';
	
	/** 导航栏 margin-right */
	const navRight = ref(0);
	
	// #ifdef MP-WEIXIN
	/** 获取小程序胶囊信息 */
	const { width } = uni.getMenuButtonBoundingClientRect()
	navRight.value = `${width}px`;
	// #endif
	
	/** 阅读倒计时 */
	const readTime = ref(0);
	
	/** 阅读倒计时对象 */
	const readTimer = ref(null);
	
	/** 增加阅读计时 */
	const increaseReadTime = () => {
	    readTime.value += 1;
	};
	
	/** 阅读倒计时计算方法 */
	const formattedReadTime = computed(() => {
	    const minutes = Math.floor(readTime.value / 60);
	    const seconds = readTime.value % 60;
	    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
	});
	
	/** 清楚阅读倒计时 */
	const clearReadTimeInterval = () => {
		clearInterval(readTimer.value);
		readTimer.value = null;
	};
	
	/** 开启阅读倒计时方法 */
	const onInterval = () => {
		readTimer.value = setInterval(increaseReadTime, 1000)
	};
	
	
	/** props */
	const props = defineProps(['exerciseId', 'articleId']);
	
	/** loading */
	const loading = ref(true);
	
	/** 练习详情 */
	const exerInfo = ref({});
	const getExerInfo = async () => {
		const result = await getExerDetail_api({ id: props.exerciseId });
		exerInfo.value = result;
		loading.value = false;
	};
	
	/** 文章播放状态 */
	const isplayStatus = ref(false);
	
	/** 关闭文章播放状态 */
	const closePlay = () => {
		isplayStatus.value = false;
	};
	
	/** 音频自然播放结束事件  */
	uni.useAudio.onEnded(closePlay);
	
	/** 音频播放事件  */
	uni.useAudio.onPlay(() => {
		isplayStatus.value = true
	});
	
	/** 音频停止事件  */
	uni.useAudio.onStop(closePlay);
	
	/** 文章播放方法 */
	function playEvent() {
		if (!topicData.value?.voiceFile?.url) {
			return;
		};
		
		if (!isplayStatus.value) uni.useAudio.src(topicData.value?.voiceFile?.url);
		else {
			uni.useAudio.pause();
			isplayStatus.value = false;
		};
	};
	
	
	/** 题目列表 */
	const topicData = ref({});
	
	/** 是否退出当前页面 */
	const usOutPage = ref(false);
	
	/** 获取题目列表方法 */
	const getTopiclist = async () => {
		const result = await getArticleDetail_api({ id: props.articleId });
		topicData.value = result;
		
		uni.closeSocket({
			fail: () => {}
		});
		
		if (!result?.voiceFile?.url || !result?.questions?.length) {
			setTimeout(async () => {
				if (usOutPage.value) return;
				await getTopiclist();
				
			}, 1000);
		};
	};
	
	
	/** 监听WebSocket接受到服务器的消息事件  */
	uni.onSocketMessage(async result => {
		if (result.data === 'questionDone') {
			uni.closeSocket({
				fail: () => {}
			});
			await getTopiclist();
		};
	});
	
	
	/** 文章段落 */
	const isTranslation = ref(false);
	const { proxy } = getCurrentInstance();
	const courseArticleParagraphlist = ref([]);
	const courseArticleParagraphIndex = ref(-1);
	const getCourseArticleParagraphs = async () => {
		const result = await readApi.courseArticleParagraphs({ articleId: props.articleId });
		courseArticleParagraphlist.value = result;
		if (!result?.find(item => item.english)) {
			uni.$fui.modal({
				showCancel: false,
				confirmColor: '#1abc9c',
				content: '文章解析失败~',
				success: () => {
					uni.navigateBack();
				}
			});
			
			return;
		};
		
		nextTick(() => {
			uni.createSelectorQuery()
				.in(proxy)
				.selectAll('.translation-view .translation-view-text')
				.boundingClientRect(result => {
					result.forEach((item, index) => {
						courseArticleParagraphlist.value[index].rect = item;
					});
				})
				.exec();
		});
	};
	getCourseArticleParagraphs();
	
	
	/** 倒计时时间 */
	const timeElapsed = ref(0);
	
	/** 增加倒计时 */
	const countup = () => {
	    timeElapsed.value += 1;
	};
	
	/** 答题弹窗实例 */
	const ExamPopupRef = ref({});
	
	/** 答题倒计时对象 */
	let timer = null;
	
	/** 开始做题/解析 */
	async function handleStart() {
		if (!topicData.value?.questions?.length) {
			uni.$fui.toast('题目还在生成中...');
			return;
		};
		
		uni.setStorageSync('aireading:article:questions', topicData.value);
		uni.$fui.href('/pages/course/aireading/answer-page', { ...props, readTime: readTime.value, analyze: isselect.value ? 1 : 0 });
		// ExamPopupRef.value.open()
		// if (!isread.value && !timer) {
		// 	timer = setInterval(countup, 1000);
		// };
	};
	
	/** 暂停倒计时 */
	const handleExamPopup = ({ show }) => {
		!show && clearInterval(timer);
		show && timer && (timer = setInterval(countup, 1000));
	};
	
	/** 保存答案 */
	async function takeFun({ index, data }) {
		topicData.value.questions[index].answer = data.answer;
		// await readApi.answer({ readId: props.readId, answers: [{ id: topicData.value.article.questions[index].id, answer: data.answer }] });
	};
	
	/** 阅读结束练习 */
	async function handleSubmit(data) {
		/** 所有答案 */
		const answers = topicData.value?.questions.map(({ id, answer }) => ({ id, answer })).filter(item => item.answer);
		
		if (!answers.length) {
			uni.$fui.toast('请先答题哦');
			return false;
		};
		
		uni.$fui.modal({
			title: '提示',
			content: '确定是否提交答案？',
			success: async () => {
				clearInterval(timer);
				submitData.answers = data;
				await readApi.answer({ readId: props.readId, answers });
				await readApi.submit({ readId: props.readId, useTime: timeElapsed.value, readTime: readTime.value });
				uni.redirectTo({ 
					url: `/pages/course/aireading/result?id=${props.articleId}` 
				});
			}
		})
	};
	
	
	/** 答题组件实例 */
	const examRef = ref({});
	
	/** 答题卡点击 */
	function cardEvent() {
		examRef.value.stepStatus = examRef.value.stepStatus === 2 ? 1 : 2;
	};
	
	/** 倒计时计算方法 */
	const formattedTime = computed(() => {
	    const minutes = Math.floor(timeElapsed.value / 60);
	    const seconds = timeElapsed.value % 60;
	    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
	});
	
	
	/** 查看生词本 */
	function goWord() {
		uni.navigateTo({
			url: `/pages/course/aireading/newWord?id=${props.articleId}`
		});
	};
	
	
	/** text 实例 */
	const reactextRef = ref([]);
	
	/** 生词标记状态 */
	const reactextStatus = ref(false);
	
	/** 是否显示标记生词 */
	function switchStatus() {
		let show = false;
		reactextRef.value.forEach(item => {
			const _show = item?.changeStatus?.();
			if (_show) show = true;
		});
		
		if (show) reactextStatus.value = !reactextStatus.value;
	};
	
	
	/** 是否解析模式 */
	const isselect = ref(false);
	
	/** 设置生词 */
	const setNewWord = async () => {
		const result = await getArticleWordsList_api({ articleId: props.articleId, type: 2 });
		setTimeout(() => {
			nextTick(() => {
				reactextRef.value.forEach(item => {
					item?.setNewWord?.(result);
				});
			});
		}, 20)
	};
	
	/** 进入页面时 */
	onShow(async () => {
		await getExerInfo();
		isselect.value = exerInfo.value?.status?.value === 2;
		onInterval();
		await setNewWord();
		await getTopiclist();
	});
	

const { fontStatus, font_title, font_cons, setupFontFun } = useFont()

const detail = ref({})
const articleRef = ref()
const userId = ref(0);






// 用户的答案列表，在练习详情接口来拿
const useranswerlist = ref([])
const isread = ref(false)
const wordlist= ref([])
onLoad(async o => {
	// submitData.exerciseId = 1
	// userId.value = o.userId || 0;
	// if(o.read) {
	// 	isselect.value = true
	// 	let res = await getExerDetail_api({id: submitData.exerciseId})
	// 	useranswerlist.value = res.log.answer
	// 	// res.log.answer.forEach(item => {
			
	// 	// })
	// } 
	// detail.value = await getArticleDetail_api({id: 12, terminal: 'applet'})
	// wordlist.value = await getArticleWordsList_api({articleId: detail.value.id})
	// if(o.read){
	// 	isread.value = true
	// }
}) 


function handleRank(id){
	uni.redirectTo({
		url: `/pages/course/reading/info?rankId=${id}&examId=${submitData.exerciseId}`
	})
}


onBeforeUnmount(() => {
	console.log('卸载了组件')
	isplayStatus.value = false
	clearInterval(timer)
	clearReadTimeInterval();
	uni.useAudio.pause();
	usOutPage.value = true;
})
onHide(() => {
	console.log('隐藏了页面')
	isplayStatus.value = false
	clearInterval(timer)
	clearReadTimeInterval();
	uni.useAudio.pause();
	usOutPage.value = true;
})



const popupRef = ref()
const isListShow = ref(false)
function selectListEvent(){
	popupRef.value.open('bottom')
}

function popupStatusEvent(data){
	isListShow.value = data.show
}

const submitData = reactive({
	logId: 0,
	exerciseId: 0,
	answers: []
})








function goMark(){
	if (!wordlist.value?.length) {
		uni.showToast({ icon: 'none', title: '请先加入生词哦~' });
		return;
	};
	
	uni.navigateTo({
		url: `/pages/course/reading/mark?articleId=${detail.value.id}&userId=${userId.value}`
	})
}
</script>

<style lang="scss" scoped>
.bottombox{padding: 20rpx 32rpx;}
.btn{height: 90rpx; border-radius: 30rpx; flex: 1; text-align: center; line-height: 80rpx; color: #fff; font-size: 32rpx; display: flex; align-items: center; justify-content: center;}
.btn+.btn{margin-left: 20rpx;}		

.time{position: absolute; right: 20rpx; top: 40rpx;}
.timeicon{width: 30rpx; height: 30rpx;}

.mp3icon{ display: flex; flex-flow: row nowrap; align-items: center; justify-content: space-between; width: 30rpx; margin-left: 20rpx;}
.mp3icon .item{width: 4rpx;height: 14rpx;background-color: #fff;}

.mp3icon .item:nth-of-type(1) {
  animation: grow 1s -0.45s ease-in-out infinite;
}

.mp3icon .item:nth-of-type(2) {
  animation: grow 1s -0.3s ease-in-out infinite;
}

.mp3icon .item:nth-of-type(3) {
  animation: grow 1s -0.15s ease-in-out infinite;
}

.mp3icon .item:nth-of-type(4) {
  animation: grow 1s ease-in-out infinite;
}

@keyframes grow {
  0%,
  100% {
    transform: scaleY(1);
  }

  50% {
    transform: scaleY(2);
  }
}

.shadow{box-shadow: 0 0 10rpx rgba(0,0,0,0.5)}
</style>